package com.magist.manage.web.facade.impl;

import com.magist.core.exception.BusinessException;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.TxtUtil;
import com.magist.manage.web.dto.UserInfoDto;
import com.magist.manage.web.entity.UserInfo;
import com.magist.manage.web.entity.UserLogin;
import com.magist.manage.web.facade.UserFacade;
import com.magist.manage.web.service.UserInfoService;
import com.magist.manage.web.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserFacadeImpl implements UserFacade {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserLoginService userLoginService;

    @Override
    public void addUser(UserInfoDto userInfoDto) {
        Assert.notNull(userInfoDto.getUserName(), "姓名为空");
        Assert.notNull(userInfoDto.getLoginName(), "登录名为空");
        Assert.notNull(userInfoDto.getPassword(), "密码为空");
        Assert.notNull(userInfoDto.getUserStatus(), "用户状态未选");
        Assert.notNull(userInfoDto.getUserType(), "用户类型未选");
        // 查询用户名是否重复
        boolean flag = this.checkLoginName(userInfoDto.getLoginName());
        if (!flag) {
            throw new BusinessException("账号已被占用");
        }
        UserInfo userInfo = BeanCopyUtil.copy(userInfoDto, UserInfo.class);
        userInfo.setId(userInfoService.getNewId());
        userInfoService.insert(userInfo);

        UserLogin userLogin = BeanCopyUtil.copy(userInfoDto, UserLogin.class);
        userLogin.setId(userInfo.getId());
        userLogin.setTel(userInfoDto.getTel());
        userLogin.setEmail(userInfoDto.getEmail());

        userLogin.setPassword(TxtUtil.digest(userLogin.getPassword()));
        userLoginService.insert(userLogin);
    }

    private boolean checkLoginName(String loginName) {
        UserLogin userLogin = new UserLogin();
        userLogin.setLoginName(loginName);
        List<UserLogin> userLogins = userLoginService.find(userLogin);
        if (!CollectionUtils.isEmpty(userLogins)) {
            return false;
        }
        return true;
    }
}
